package curves.gui;

import java.awt.Component;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import curves.CurveAlgorithm;
import curves.Surface;
import curves.math.BezierCurveAlgorithm;
import curves.math.C2SplineCurveAlgorithm;
import curves.math.ChaikinCurveAlgorithm;
import curves.math.DeCasteljanCurveAlgorithm;
import curves.math.C1SplineCurveAlgorithm;
import curves.math.CatmullRomCurveAlgorithm;

public class AlgorithmDialog extends JDialog {

    private JComboBox comboBox;
    private JButton button;
    private JPanel panel;
    private JLabel label;
    private Surface surface;
    private Window window;

    public AlgorithmDialog(Window aFrame, Surface surface) {
        super(aFrame, true);
        this.surface = surface;
        this.window = aFrame;
        panel = new JPanel();
        label = new JLabel("Choose algorithm:");
        label.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(label);

        comboBox = new JComboBox();
        comboBox.addItem(new C1SplineCurveAlgorithm());
        comboBox.addItem(new ChaikinCurveAlgorithm());
        comboBox.addItem(new C2SplineCurveAlgorithm());
        comboBox.addItem(new DeCasteljanCurveAlgorithm());
        comboBox.addItem(new BezierCurveAlgorithm());
        comboBox.addItem(new CatmullRomCurveAlgorithm());

        comboBox.setAlignmentX(Component.CENTER_ALIGNMENT);
        comboBox.addActionListener(new SelectionListener());
        panel.add(comboBox);


        button = new JButton("Ok");
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        button.addActionListener(new OkButtonListener());
        panel.add(button);

        getContentPane().add(panel);

        pack();
        setResizable(false);

    }

    void setSelectedAlgorithm(String algo) {
        for(int i = 0; i < comboBox.getItemCount(); i++){
            if(comboBox.getItemAt(i).toString().equals(algo)){
                comboBox.setSelectedIndex(i);
                break;
            }
        }
    }

    class OkButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            AlgorithmDialog.this.setVisible(false);
        }
    }

    class SelectionListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox) e.getSource();
            CurveAlgorithm algorithm = (CurveAlgorithm) cb.getSelectedItem();
            surface.getCurrentCurve().setCurveAlgorithm(algorithm);
            surface.getCurrentCurve().updateCurve(null);
            window.getGraphicEngine().repaint();
        }
    }
}
